import { UserSwitchOutlined } from '@ant-design/icons'
import { truthy } from '@gnlab/utils'
import { useBoolean } from '@gnlab/utils/env-react'
import type { MemStream } from '@gnlab/utils/rx'
import { Tooltip, Modal, Input, message } from 'antd'
import { ChooseAccountInput } from '@/desktop/components/ChooseAccount'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import type { BaseAccount } from '@/services/auth'
import type { ExternalContact } from '@/services/contact-types/externals'
import { ContactType } from '@/services/contacts'
import './index.module.less'

export default function Transfer() {
  const [contact] = useStreams(services.contacts.current.contact)
  const [transfering, startTransfer, finishTransfer] = useBoolean(false)
  const [transfers] = useStreams(services.transfers.list)
  if (!contact || contact.type !== ContactType.external || transfers.has(contact.id)) return null

  return <div>
    <Tooltip title="转交客户">
      <UserSwitchOutlined onClick={startTransfer} styleName="icon" />
    </Tooltip>

    <TransferModal visible={transfering} onClose={finishTransfer} />
  </div>
}

function TransferModal(props: { visible: boolean; onClose: () => void }) {
  const { visible, onClose } = props
  const [contact, account] = useStreams(
    services.contacts.current.contact as MemStream<ExternalContact>,
    services.auth.account$,
  )

  const [msg, setMsg] = useState<string | null>(null)
  const [target, setTarget] = useState<BaseAccount | null>(null)
  const [remark, setRemark] = useState('')
  const [submitting, setSubmitting] = useState(false)

  function changeTarget(t: BaseAccount | null) {
    setMsg(null)
    setTarget(t)
  }
  function reset() {
    setMsg(null)
    setTarget(null)
    setRemark('')
    onClose()
  }
  async function submit() {
    if (!target) {
      setMsg('请选择要转交给谁')
    } else {
      setSubmitting(true)
      const res = await services.transfers.transfer({ contact, targetAccount: target, remark })
      setSubmitting(false)

      if (res.success) {
        void message.success('转交成功！')
        reset()
      } else {
        void message.error(`转交失败：${res.error}`)
      }
    }
  }

  return <Modal
    title="客户转交"
    closable
    maskClosable={false}
    open={visible}
    confirmLoading={submitting}
    onCancel={reset}
    onOk={submit}
    destroyOnClose
  >
    <div styleName="content">
      <section>
        <label>选择转交对象：</label>
        <ChooseAccountInput
          disabled={account?.id}
          value={target ? target.id : null}
          onChange={(id, target) => changeTarget(target)}
        />
        {truthy(msg) ? <div styleName="msg">{msg}</div> : null}
      </section>
      <section>
        <label>转交附言：</label>
        <Input.TextArea
          showCount
          maxLength={200}
          rows={4}
          value={remark}
          onChange={e => setRemark(e.target.value)}
        />
      </section>
      <section styleName="tips">转交后，你和对方均可与该客户聊天。</section>
    </div>
  </Modal>
}
